package com.ruizhong.centercontroll.util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RecognizeAudioByBaidu {
    public static final String API_KEY = "6GpGNKIciXBdQInO1g5WU0qm";
    public static final String SECRET_KEY = "A1OK7kyxfVtDBlhaqcBmtoh9Z6u1rlGy";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void recognize(File file) throws IOException, JSONException {
        String base64String = convertFileToBase64(file);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"format\":\"wav\",\"rate\":16000,\"channel\":1,\"cuid\":\"my_device\",\"dev_pid\":1537,\"speech\":\""+base64String+"\",\"len\":"+file.length()+",\"token\":\"" + getAccessToken() + "\"}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/server_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());

    }

private static String convertFileToBase64(File file){
    StringBuilder base64StringBuilder = new StringBuilder();

    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        // 读取文件内容到ByteArrayOutputStream
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }

        // 获取字节数组
        byte[] fileBytes = byteArrayOutputStream.toByteArray();

        // 使用Java 8的Base64工具类进行编码
        String base64Encoded = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            base64Encoded = Base64.getEncoder().encodeToString(fileBytes);
        }

        // 添加到StringBuilder（这一步是多余的，因为直接返回字符串即可，这里只是为了展示如何拼接）
        base64StringBuilder.append(base64Encoded);

    } catch (IOException e) {
        e.printStackTrace();
    }

    // 实际上可以直接返回base64Encoded字符串，不需要StringBuilder
    return base64StringBuilder.toString();
}
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
